package com.zysc.processflow.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * swagger 配置
 * API 访问路径 ：   http://IP:Port/{server.servlet.context-path}/swagger-ui/index.html
 * http://localhost:8090/zysc_processflow_api/swagger-ui/index.html
 * */
@Configuration
@EnableOpenApi
public class SwaggerConfig {


    @Value("${swagger.enable:true}")
    private boolean enableSwagger;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .enable(enableSwagger)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zysc.processflow.controller"))
                .apis(RequestHandlerSelectors.withClassAnnotation(RequestMapping.class))
//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .globalResponses(HttpMethod.GET, getGlobalResonseMessage())
                .globalResponses(HttpMethod.POST, getGlobalResonseMessage());
//                .consumes( new HashSet<>(
//                        Arrays.asList(
//                                "application/*+json",
//                                "application/json",
//                                "text/json")))
//                .produces( new HashSet<>(
//                        Arrays.asList(
//                                "text/plain",
//                                "application/json",
//                                "text/json")));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .description("适用于前后端分离统一的接口文档")
                .version("1.0")
                .build();
    }

    //    @Bean
//    public SecurityConfiguration securityConfiguration() {
//        return SecurityConfigurationBuilder.builder()
//                .enableCsrfSupport(true)
//                .build();
//    }
//
////    @Bean
//    public Docket createRestApi() {
//        //返回文档摘要信息
//        return new Docket(DocumentationType.OAS_30)
//                .apiInfo(apiInfo())
//                .select()
//                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//                .apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
//                .paths(PathSelectors.any())
//                .build()
//                .globalRequestParameters(getGlobalRequestParameters())
//                .globalResponses(HttpMethod.GET, getGlobalResonseMessage())
//                .globalResponses(HttpMethod.POST, getGlobalResonseMessage());
//    }

    //生成全局通用参数
    private List<RequestParameter> getGlobalRequestParameters() {
        List<RequestParameter> parameters = new ArrayList<>();
//        parameters.add(new RequestParameterBuilder()
//                .name("appid")
//                .description("平台id")
//                .required(true)
//                .in(ParameterType.QUERY)
//                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
//                .required(false)
//                .build());
        Collection<MediaType> accepts = new ArrayList<MediaType>();
        accepts.add(MediaType.APPLICATION_JSON);
//        parameters.add(new RequestParameterBuilder().accepts(accepts).build());
        return parameters;
    }

    //生成通用响应信息
    private List<Response> getGlobalResonseMessage() {
        List<Response> responseList = new ArrayList<>();
//        ResponseBuilder builder = new ResponseBuilder();
//        builder.representation(MediaType.APPLICATION_JSON).apply(new Consumer<RepresentationBuilder>() {
//            @Override
//            public void accept(RepresentationBuilder representationBuilder) {
//                representationBuilder.mediaType(MediaType.APPLICATION_JSON);
//            }
//        });
//        responseList.add(builder.build());
//        responseList.add(new ResponseBuilder().code("404").description("找不到资源").build());
        responseList.add(new ResponseBuilder()
                .code("200")
                .description("Success")
                .representation(MediaType.APPLICATION_JSON)
                .apply(r -> r.model(m -> m.scalarModel(ScalarType.STRING))
                        .build())
                .representation(MediaType.TEXT_PLAIN)
                .apply(r -> r.model(m -> m.scalarModel(ScalarType.STRING)))
                .build());
        return responseList;
    }
    // 解决springboot2.6.1 和swagger3.0 版本问题
//    @Bean
//    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
//        return new BeanPostProcessor() {
//
//            @Override
//            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
//                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
//                }
//                return bean;
//            }
//
//            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
//                List<T> copy = mappings.stream()
//                        .filter(mapping -> mapping.getPatternParser() == null)
//                        .collect(Collectors.toList());
//                mappings.clear();
//                mappings.addAll(copy);
//            }
//
//            @SuppressWarnings("unchecked")
//            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
//                try {
//                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
//                    field.setAccessible(true);
//                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
//                } catch (IllegalArgumentException | IllegalAccessException e) {
//                    throw new IllegalStateException(e);
//                }
//            }
//        };
//    }
}
